<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import {io} from 'socket.io-client'
import type {Socket} from 'socket.io-client'
import {onMounted,ref,nextTick,provide} from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import {getConsultOrderDetail} from '@/services/consult'
import { showToast } from 'vant';
import dayjs from 'dayjs'
const store=useUserStore()
let socket:Socket
const list=ref<Message[]>([])
onMounted(() => {
    // 连接
    socket=io(baseURL,{
        // 身份验证
        auth:{
            token:`Bearer ${store.user?.token}`
        },
        // 订单ID
        query:{
            orderId:route.query.orderId
        }
    })
    socket.on('connect',()=>{
      list.value=[]
    })
    // 初始化的默认信息
    socket.on('chatMsgList',({data}:{data:TimeMessages[]})=>{
        const arr:Message[] =[] 
        data.forEach((item,i) => {
          if (i === 0) time.value = item.createTime
            arr.push({
                msgType:MsgType.Notify,
                msg:{content:item.createTime},
                createTime:item.createTime,
                id:item.createTime
            })
            // arr.push(...item.items)
            item.items.forEach((item)=>{
              arr.push({...item,notScroll:initMsg.value===false})
            })

        })
        list.value.unshift(...arr)
        loading.value=false
        if (!data.length) {
          return showToast('没有更多聊天记录了')
        }
        // 第一次加载到最底部
        nextTick(()=>{
          if (initMsg.value) {
            window.scrollTo(0,document.body.scrollHeight)
            socket.emit('updateMsgStatus',arr[arr.length-1].id)
            initMsg.value=false
          }
        })
    })
    // 订单状态信息
    socket.on('statusChange',async ()=>{
      const res=await getConsultOrderDetail(route.query.orderId as string)
      consult.value=res.data
    })
    // 接收信息
    socket.on('receiveChatMsg',async (msg:Message)=>{
      list.value.push(msg)
      await nextTick()
      socket.emit('updateMsgStatus',msg.id)
      window.scrollTo(0,document.body.scrollHeight)
    })
})
const consult=ref<ConsultOrderItem>()
const route=useRoute()
onMounted(async () => {
    const res=await getConsultOrderDetail(route.query.orderId as string)
    consult.value=res.data
})
// 发送文字信息
const sendText= (text:string)=>{
    socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType:MsgType.MsgText,
    msg:{
      content:text
    }
  })
}
// 发送图片信息
const sendImg=(img:Image)=>{
  socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType:MsgType.MsgImage,
    msg:{
      picture:img
    }
  })
}

const initMsg=ref(true)

const loading=ref(false)
const time=ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

const onRefresh=async ()=>{  
  socket.emit('getChatMsgList',20,time.value,consult.value?.id)
}

provide('consult',consult)
const completeEva =(score:number)=>{
const item=list.value.find(item=> item.msgType===MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc={score}
    item.msgType=MsgType.CardEva
  }
}
provide('completeEva',completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown"/>
    
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action @sent-text="sendText" @sent-img="sendImg" :disabled="consult?.status!==OrderType.ConsultChat "></room-action>

  </div>
</template>


<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>

